package com.warrior.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.warrior.Exception.ProjectException;
import com.warrior.entity.AdminUser;
import com.warrior.service.AdminService;
import com.warrior.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * 后台管理controller
 * Created by Shawn on 2017/4/7.
 */
@Controller
@RequestMapping("/admin")
public class AdminController {


    @Autowired
    private AdminService adminService;

    /**
     * 后台导航栏
     *
     * @param response resp
     * @param request  req
     * @return ModelAndView
     */
    @RequestMapping("/nav")
    public ModelAndView nav(HttpServletResponse response, HttpServletRequest request) {

        ModelAndView mv = new CModelAndView("admin/navbar", request, response);
        Object userId = request.getSession().getAttribute("userId");
        if (userId != null) {
            String id = (String) userId;
            mv.addObject("userId", id);
            AdminUser userEntity = this.adminService.findAdminUserById(id);
            mv.addObject("user", userEntity);
        }
        return mv;
    }

    @RequestMapping("/admin_list")
    public ModelAndView showAdminList(HttpServletResponse response, HttpServletRequest request, String page, String size, String orderType) {
        ModelAndView mv = new CModelAndView("admin/admin_list", request, response);
        Page<AdminUser> adminUsers = this.adminService.listAllAdminUser(CommonUtils.String2Int(page), CommonUtils.String2Int(size), orderType);
        mv.addObject("adminUsers", adminUsers);
        return mv;
    }

    @RequestMapping(value = "/admin_add", method = RequestMethod.GET)
    public ModelAndView addAdminUser(HttpServletResponse response, HttpServletRequest request, String adminUserId) {
        ModelAndView mv = new CModelAndView("admin/admin_edit", request, response);
        if (null != adminUserId) {
            AdminUser adminUser = this.adminService.findAdminUserById(adminUserId);
            mv.addObject("adminUser", adminUser);
        }
        return mv;
    }

    /**
     * 添加/编辑管理员
     *
     * @param adminUserId 管理员id
     * @param userName    用户名
     * @param password    密码
     * @param userStatus  用户状态
     * @param mobile      手机号
     * @param adminType   管理员类型
     * @return
     * @throws ProjectException
     */
    @RequestMapping(value = "/admin_add", method = RequestMethod.POST)
    @ResponseBody
    public String addAdminUser(String adminUserId, String userName, String password, String userStatus, String mobile, String adminType) throws ProjectException {
        DateUtil dateUtil = new DateUtil();
        AdminUser adminUser;
        if (null == adminUserId || "".equals(adminUserId)) {
            adminUser = new AdminUser();
            adminUser.setId("AU-" + UUID.randomUUID().toString().replace("-", ""));
            adminUser.setCreatedAt(dateUtil.Date2Timestamp(new Date()));
            adminUser.setPassword(MD5Util.getMD5(password));
            adminUser.setUserName(userName);
        } else {
            adminUser = this.adminService.findAdminUserById(adminUserId);
        }
        adminUser.setMobile(mobile);
        adminUser.setUserType(CommonUtils.String2Int(adminType));
        adminUser.setUpdateAt(dateUtil.Date2Timestamp(new Date()));
        adminUser.setCreatedBy("admin");
        adminUser.setUpdateBy("admin");
        adminUser.setUserStatus(CommonUtils.String2Int(userStatus));
        this.adminService.saveAdminUser(adminUser);
        String returnMap = null;
        try {
            returnMap = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }


    @RequestMapping(value = "delete_admin_user", method = RequestMethod.DELETE)
    @ResponseBody
    public String deleteAdmin(String adminId) {
        this.adminService.deleteAdminUser(adminId);
        String returnMap = null;
        try {
            returnMap = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }


    /**
     * 验证管理员名称
     * @param userName
     * @return
     */
    @RequestMapping(value = "/validate_admin_name", method = RequestMethod.POST)
    @ResponseBody
    public String validateAdminUserName(String userName) {
        AdminUser adminUser = this.adminService.findAdminUserByName(userName);
        String returnMap = null;
        try {
            if (null == adminUser) {
                returnMap = ServerResponse.okToJsonString("success");
            } else {
                returnMap = ServerResponse.okToJsonString("用户名重复");
            }

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;


    }


}
